var zTree;
var treeObj;
var primaryData;
var setting = {
    check: {
        enable: true,
        chkStyle: "checkbox",
        chkboxType: {
            "Y": "ps",
            "N": "s"
        }
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pId",
            rootPId: null
        }
    },
    callback: {
        beforeCheck: true,
        onCheck: onCheck
    }
};
$(function () {
    var columns = [
        {
            field: 'ck',
            checkbox: true
        }, {
            field: 'name',
            title: '名称'
        },
        {
            field: 'remarks',
            title: '备注'
        },
        {
            field: 'createTime',
            title: '创建时间'
        }, {
            field: 'id',
            title: '操作',
            formatter: function (value, row, index) {
                return '<button id="btn_edit" type="button" class="btn btn-primary  btn-xs" onclick="update(\'' + value + '\')"><i class="fa fa-edit"></i>修改</button>' +
                    '<button type="button" class="btn btn-danger  btn-xs" onclick="deletes(\'' + value + '\')" style="margin-left: 10px;"><i class="fa fa-trash-o"></i> 删除</button>';
            }
        }
    ];
    createBootstrapTable($("#table"), '/admin/sysRole/info', columns, true, toolbar, 'client')



    request('/admin/sysPermission/zTreeNodes', 0, null, function (res) {
        if (res.code == 0) {

            zTree = $.fn.zTree.init($("#typeTree"), setting, res.data);
            treeObj = $.fn.zTree.getZTreeObj("typeTree");
            treeObj.expandAll(true);
            primaryData=res.data;
        } else {
            layer.msg("树表初始化失败！")
        }
    }, function (error) {
        layer.msg("系统异常！")
    })
});

// 清空表单
function clearForm() {
    $("#name").val("");
    $("#roleId").val("");
    $("#mids").val("");
    $("#remarks").val("");
    zTree = $.fn.zTree.init($("#typeTree"), setting, primaryData);
    zTree.checkAllNodes(false);
    treeObj = $.fn.zTree.getZTreeObj("typeTree");
    treeObj.expandAll(true);
}

//树形菜单选中事件
function onCheck(e, treeId, treeNode) {
    var ckid = [];
    var nodes = treeObj.getCheckedNodes(true);
    for (var n in nodes) {
        ckid.push(nodes[n].id)
    }
    $("#mids").val(ckid)
}


function doSetSelectNode(ids) {
    var treeObj = $.fn.zTree.getZTreeObj("typeTree")
    //取消所有选中等待重新赋值
    treeObj.checkAllNodes(false);
    for (var i = 0; i < ids.length; i++) {
        var node = treeObj.getNodeByParam("id", ids[i]);
        if (node != null) {
            node.checked = true;
        }
    }
    // 刷新节点状态
    treeObj.refresh()
}

var roleForm;

//新增
function add() {
    console.log(1);
    clearForm();
    console.log(2);
    roleForm = layer.open({
        type: 1,
        area: (window.innerWidth > 992) ? "600px" : "auto",
        title: '新增',
        shade: 0.6,
        shadeClose: true, //点击遮罩关闭层
        maxmin: false,
        anim: 1,
        content: $("#role_form"),
        success: function (layero, index) {
            layer.iframeAuto(index);
        }, end: function () {
            $("#role_form").hide()
        }
    });
}

function save() {
    var id = $("#roleId").val()
    var name = $("#name").val();
    var remarks = $("#remarks").val();
    var mids = $("#mids").val();
    if (name == '' || name == null) {
        layer.msg("请输入名称！");
        return
    }
    if (mids == '' || mids == null) {
        layer.msg("请选择要分配的权限！");
        return
    }

    var data = {
        id: id,
        name: name,
        remarks: remarks,
        mids: mids
    };

    request('/admin/sysRole/save', 1, data, function (res) {
        if (res.code == 0) {
            layer.close(roleForm);
            layer.msg("保存成功", {time: 1000}, function () {
                // onLoads($("#href").val())
                location.reload();
            })
        }
    }, function (error) {
        layer.msg("系统异常！")
    })
}

/**
 * 修改
 */
function update(id) {
    clearForm();
    var data = {
        id: id
    };
    request('/admin/sysRole/update', 0, data, function (res) {

        if (res.code == 0) {
            $("#name").val(res.data.role.name);
            $("#roleId").val(res.data.role.id);
            $("#mids").val(res.data.ids);
            $("#remarks").val(res.data.role.remarks);
            var ids = res.data.ids;
            doSetSelectNode(ids)
        }
    }, function (error) {
        layer.msg("系统异常！")
    });

    roleForm = layer.open({
        type: 1,
        area: (window.innerWidth > 992) ? "600px" : "auto",
        title: '修改',
        shade: 0.6,
        shadeClose: true, //点击遮罩关闭层
        maxmin: false,
        anim: 1,
        content: $("#role_form"),
        success: function (layero, index) {
            layer.iframeAuto(index);
        }, end: function () {
            $("#role_form").hide()
        }
    });
}

function deletes(id) {
    var ids = [];
    if (id != undefined) {
        ids.push(id)
    } else {
        $.each($('tbody input:checkbox:checked'), function () {
            ids.push($(this).parents('tr').data('uniqueid'));
        });
    }
    if (ids.length < 1) {
        layer.msg("最少请选择一条数据！")
        return;
    }

    var data = {
        ids: ids.toString()
    }
    layer.confirm('确定删除吗？', {
        title: '提示', btn: ['取消', '确定']
    }, function () {
        layer.close(layer.index)
    }, function () {
        request('/admin/sysRole/delete', 1, data, function (res) {
            if (res.code == 0) {
                layer.msg("删除成功", {time: 1000}, function () {
                    // onLoads($("#href").val())
                    location.reload();
                })
            } else {
                layer.msg(res.msg, {time: 1000})
            }
        }, function (error) {
            layer.msg("系统异常！")
        })
    });
}

function formSearch() {
    var name = $("#searchName").val()
    var data = {
        name: name
    };
    request('/admin/sysRole/info', 1, data, function (res) {
        $("#table").bootstrapTable('load', res);
    }, function (error) {
        layer.msg(error.msg)
    })
}

function restForm() {
    document.getElementById("searchForm").reset()
    formSearch();
}

function loadRole(res) {
    request('/admin/roleDist/info', 1, null, function (data) {
        $("#area").empty()
        for (var i = 0; i < data.length; i++) {
            $("#area").append(
                '<input type="checkbox" name="dist" class="minimal" value=' + data[i].dictValue + '><span>' + data[i].dictLabel + ''
            )
        }
        if (res != undefined) {
            $.each($('input[name=dist]'), function () {
                for (var j = 0; j < res.length; j++) {
                    if (res[j] == $(this).val()) {
                        $(this).prop("checked", true);
                    }
                }
            });
        }
    }, function (error) {
        layer.msg("系统异常！")
    })
}



